<template>
    <div >
        <div style="margin-bottom: 5px;">
            <el-input v-model="name" placeholder="请输入订单编号" suffix-icon="el-icon-search" style="width: 200px;"
                      @keyup.enter.native="loadPost"></el-input>
            <el-button type="primary" style="margin-left: 5px;" @click="loadPost">查询</el-button>
            <el-button type="success" @click="resetParam">重置</el-button>
            <el-button type="primary" style="margin-left: 5px;" @click="add">新增</el-button>
            <!--  退货申请按钮，通过selectedRows.length的长度控制是否显示  -->
            <el-button type="primary" style="margin-left: 5px;" v-show="selectedRows.length !== 0" @click="returnApply" >申请退货</el-button>
        </div>
      <!--  订单表格     -->
        <el-table :data="tableData"
                  :header-cell-style="{ background: '#f2f5fc', color: '#555555' }"
                  border
                  @selection-change="handleSelectionChange"
                  :row-key="row => row.id"
        >
            <!-- 每行开头的多选，可以进行退货申请  -->
            <el-table-column type="selection" width="60" align="center" reserve-selection :selectable="row => row.status !== 4">
            </el-table-column>
            <el-table-column prop="id" label="编号" width="60">
            </el-table-column>
            <el-table-column prop="name" label="订单编号" width="180">
            </el-table-column>
            <el-table-column prop="createTime" label="提交时间" :formatter="formatCreateTime">
            </el-table-column>
            <el-table-column prop="memberUsername" label="用户账号">
            </el-table-column>
            <el-table-column prop="totalAmount" label="订单总金额" :formatter="formatAmount">
            </el-table-column>
            <el-table-column prop="payType" label="支付方式" :formatter="formatPayType">
            </el-table-column>
            <el-table-column prop="status" label="状态" :formatter="formatStatus">
            </el-table-column>
            <el-table-column prop="operate" label="操作">
                <template slot-scope="scope">
                    <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
                    <el-popconfirm
                            title="确定删除吗？"
                            @confirm="del(scope.row.id)"
                            style="margin-left: 5px;"
                    >
                        <el-button slot="reference" size="small" type="danger" >删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!--  分页组件，显示页数以及更改单页显示数     -->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[5, 10, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
        <!--  提示框：编辑或添加商品    -->
        <el-dialog
                title="提示"
                :visible.sync="centerDialogVisible"
                width="30%"
                center>

            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="订单编号" prop="name">
                    <el-col :span="20">
                        <el-input v-model="form.name"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="总金额" prop="totalAmount">
                    <el-col :span="20">
                        <el-input v-model="form.totalAmount"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="支付方式" prop="payType">
                    <el-col :span="20">
                        <el-select v-model="form.payType" clearable placeholder="请选择支付方式" @change="handlePayTypeChange">
                            <el-option v-for="item in payTypeOptions" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-col :span="20">
                        <el-select v-model="form.status" clearable placeholder="请选择订单状态" :disabled="isStatusDisabled">
                            <el-option v-for="sitem in statusOptions" :key="sitem.value" :label="sitem.label" :value="sitem.value">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
            </span>
        </el-dialog>
      <!-- 抽屉组件 -->
      <el-drawer
          title="申请退货"
          :visible.sync="drawerVisible"
          direction="rtl"
          size="30%"
      >
        <div style="margin-left: 10px">
          <div style="margin-left: 10px;margin-bottom: 10px">
            <div style="margin-bottom: 10px">联系电话：<input style="height: 10px; padding: 5px;" type="tel" placeholder="请输入联系电话" v-model="applyPhone"></div>
            <div>申请人名称：<input style="height: 10px; padding: 5px;" type="text" placeholder="请输入申请人名称" v-model="applyName"></div>
          </div>
          <div style="margin-left: 10px;padding-right: 10px" v-for="(item, index) in selectedRows" :key="index">
            <h3 style="margin:10px;margin-left: 0px">订单编号：{{ item.name }}</h3>
            <!-- 退货原因选择器 -->
            <p >退货原因：
              <el-select clearable v-model="item.returnReason" placeholder="请选择退货原因">
                <el-option
                    v-for="reason in returnReasonOptions"
                    :key="reason.value"
                    :label="reason.label"
                    :value="reason.value">
                </el-option>
              </el-select>
            </p>
            <!-- 具体描述富文本框 -->
            <p >具体描述：
              <el-input
                  style="margin-top: 10px"
                  type="textarea"
                  v-model="item.description"
                  placeholder="请输入具体描述">
              </el-input>
            </p>
          </div>

        </div>
        <div style="margin-top: 20px;margin-left: 20px">
          <el-button @click="cancelApply">取消</el-button>
          <el-button type="primary" @click="submitApply">提交申请</el-button>
        </div>
      </el-drawer>
    </div>
</template>
<script>
    import {formatDate} from '@/utils/date';
    import { mapState, mapActions } from 'vuex';
    // import {getIncrease} from '../DateUtils.vue'
    export default {
        name: "OrderList",
        data() {
            return {
                tableData: [],
                pageSize:10,
                pageNum:1,
                total:0,
                name:'',
                centerDialogVisible:false,
                form:{
                    id:'',
                    name:'',
                    createTime:'',
                    totalAmount:'',
                    memberUsername:'null',
                    payType:'',
                    status:''
                },
                payTypeOptions:[
                    {value:0,label:'未支付'},
                    {value:1,label:'支付宝'},
                    {value:2,label:'微信'}
                ],
                statusOptions:[
                    {value:0,label:'待支付'},
                    {value:1,label:'待发货'},
                    {value:2,label:'已发货'},
                    {value:3,label:'已收货'},
                    {value:4,label:'已关闭'},
                ],
                returnReasonOptions: [
                  {
                    value:'',
                    label:'',
                  }
                ],
                rules: {
                    name: [
                        {required: true, message: '请输入订单编号', trigger: 'blur'}
                    ]
                },
                user : JSON.parse(sessionStorage.getItem('CurUser')),
                isStatusDisabled: false, // 控制状态选择框是否禁用
                nextOrderId: '', // 用于存储生成的订单编号
                lastId:0,
                now:'',
                selectedRows: [], // 新增属性，存储选中的行
                applyName:null,
                applyPhone:null,
                drawerVisible: false, // 控制抽屉的显示和隐藏
            }
        },
        methods:{
            ...mapActions(['fetchOrderSettings']),
            //将选中的行赋值给selectedRows
            handleSelectionChange(val) {
              this.selectedRows = val; // 更新选中的行
            },
            //加载退货原因，需要加在beforeMount中
            loadReturnReasons(){
                this.$axios.get(this.$httpUrl+'/returnApply/list/1').then(res=>res.data)
                    .then(res=>{
                        console.log(res.data)
                        if(res.code==200){
                          // 假设返回的数据在 res.data.data 中
                          this.returnReasonOptions = res.data.map(item => ({
                            value: item.name, // 使用 id 作为 value
                            label: item.name // 使用 name 作为 label
                          }));
                        }
                    console.log(this.returnReasonOptions);
                    }).catch(error => {
                        console.error('Error loading return reasons:', error);
                });
            },
            //取消退货申请，清空抽屉的信息
            cancelApply(){
              this.applyName=null;
              this.applyPhone=null;
              this.drawerVisible = false;
            },
            //显示抽屉
            returnApply(){
              this.drawerVisible = true;
            },
            //验证联系电话格式
            validatePhone(phone) {
              const phoneRegex = /^[0-9]{10,11}$/; // 简单的电话号码正则表达式，假设电话号码为10到11位数字
              return phoneRegex.test(phone);
            },
            submitApply(){
              // 检查选中的行中是否有退货原因为空的情况
              const hasEmptyReturnReason = this.selectedRows.some(row => !row.returnReason);
              if (hasEmptyReturnReason) {
                // 如果有退货原因为空，则弹出提示框
                this.$message({
                  message: '请为所有选中的订单选择退货原因！',
                  type: 'warning'
                });
                return; // 终止方法执行
              }
              //验证申请人名称以及电话
              if (this.applyName == null || this.applyPhone == null) {
                this.$message({
                  message: '请填写申请人名称及联系电话！',
                  type: 'warning'
                });
                return; // 终止方法执行
              }
              // 验证电话号码格式
              if (!this.validatePhone(this.applyPhone)) {
                this.$message({
                  message: '请输入有效的电话号码！',
                  type: 'warning'
                });
                return; // 终止方法执行
              }
              // 遍历每个订单，单独发送 POST 请求
              this.selectedRows.forEach(row => {
                const returnApplyData = {
                  orderSn: row.name,
                  createTime: this.now,
                  memberUsername: this.user.no,
                  returnAmount: row.totalAmount,
                  productRealPrice: row.totalAmount,
                  reason: row.returnReason,
                  description: row.description || null,
                  status:0,
                  productCount:1,
                  returnName:this.applyName,
                  returnPhone:this.applyPhone
                };
                console.log("提交订单", returnApplyData);
                this.$axios.post(this.$httpUrl + '/orderReturnApply/save', returnApplyData)
                    .then(res => {
                      console.log(res);
                      if (res.data.code == 200) {
                        this.$message({
                          message: '操作成功！',
                          type: 'success'
                        });
                      } else {
                        this.$message({
                          message: '操作失败！',
                          type: 'error'
                        });
                      }
                    })
                    .catch(error => {
                      console.error('Error submitting return application:', error);
                      this.$message({
                        message: '提交失败，请重试！',
                        type: 'error'
                      });
                    });
              });
              this.drawerVisible = false;
            },
            //获取当前系统时间
            getTime(){
              if (this.$store.getters.getUserSelectedTime==null){
                this.now =  new Date();
              }else{
                this.now = this.$store.getters.getUserSelectedTime;
              }
            },
            //根据生成订单编号
            generateOrderId() {
              this.getTime()
              const now = this.now
              console.log(now)
              const year = this.getIncrease(now.getFullYear(), 4);
              const month = this.getIncrease(now.getMonth() + 1, 2);
              const day = this.getIncrease(now.getDate(), 2);
              const baseOrderId = `${year}${month}${day}01010`;
              this.nextOrderId = `${baseOrderId}${this.generateSequenceNumber()}`;
            },
            generateSequenceNumber() {
                // 从 localStorage 获取 lastId，如果不存在则默认为 0
                this.lastId = parseInt(localStorage.getItem('lastId')) || 0;
                // 返回填充了前导零的序列号
                return this.lastId.toString().padStart(5, '0');
            },
            handlePayTypeChange(value) {
              this.$nextTick(() => {
                if (value === 0) { // 未支付
                  this.form.status = 0; // 待付款
                  this.isStatusDisabled = true; // 禁用状态选择框
                } else {
                  this.isStatusDisabled = false; // 启用状态选择框
                }
              })
            },
            formatCreateTime(row){
                let date = new Date(row.createTime);
                return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
            },
            formatAmount(row){
                let amount = '￥'+row.totalAmount
                return amount
            },
            formatPayType(row) {
                const payTypeMap = {
                    0: '未支付',
                    1: '支付宝',
                    2: '微信',
                };
                return payTypeMap[row.payType] || '未支付'
               
            },
            // 计算时间差（秒）
            calculateTimeDifference(createTime) {
              const orderTime = new Date(createTime);
              const currentTime = this.now || new Date();
              return (currentTime - orderTime) / 1000; // 返回秒数
            },
            formatStatus(row){
                const timeDiff = this.calculateTimeDifference(row.createTime);
                const normalOrderOvertime = this.orderSetting.normalOrderOvertime * 60
                const confirmOvertime = this.orderSetting.confirmOvertime * 24 * 60 * 60
                const commentOvertime = this.orderSetting.commentOvertime * 24 * 60 * 60
                const statusMap = {
                    0:'待支付',
                    1:'待发货',
                    2:'已发货',
                    3:'已收货',
                    4:'已关闭',
                };
                console.log(row)
                if(row.status === 0 && timeDiff > normalOrderOvertime)
                  row.status = 4
                if((row.status === 2 || row.status === 1) && timeDiff > confirmOvertime)
                  row.status = 3
                if (row.status === 3 && timeDiff > commentOvertime)
                  row.status = 4
                return statusMap[row.status] || '无效订单'
            },
            resetForm() {
                this.$refs.form.resetFields();  //this.$refs.form：这是Vue中的一种访问子组件实例的方法，$refs是一个特殊的属性，用于访问模板中DOM元素或子组件实例的引用。在这里，form是模板中表单元素的ref属性值。
                //resetFields()：这是Element UI表单组件提供的一个方法，用于重置表单内所有字段到初始状态，包括输入框、选择框等。
            },
            del(id){
                console.log(id)
                this.$axios.get(this.$httpUrl+'/order/del?id='+id).then(res=>res.data).then(res=>{
                    console.log(res)
                    if(res.code==200){

                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.loadPost()
                    }else{
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }

                })
            },
            mod(row){
                this.centerDialogVisible = true
                this.$nextTick(()=>{
                    //赋值到表单
                    this.form.id = row.id
                    this.form.name = row.name
                    this.form.totalAmount = row.totalAmount
                    this.form.payType = row.payType
                    this.form.status = row.status
                })
            },
            add(){
                this.generateOrderId(); // 生成订单编号
                this.centerDialogVisible = true
                this.$nextTick(()=>{
                    this.resetForm()
                    this.form.name = this.nextOrderId; // 将生成的订单编号赋值给表单
                })
            },
            doSave(){
                this.form.memberUsername=this.user.no
                this.form.createTime=this.now
                this.$axios.post(this.$httpUrl+'/order/save',this.form).then(res=>res.data).then(res=>{
                    console.log(res)
                    if(res.code==200){
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false
                        this.loadPost()
                        this. resetForm()
                    }else{
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })
                // 增加 lastId 并确保它是唯一的
                this.lastId += 1;
                // 将更新后的 lastId 存回 localStorage
                localStorage.setItem('lastId', this.lastId.toString());
            },
            doMod(){
                this.$axios.post(this.$httpUrl+'/order/update',this.form).then(res=>res.data).then(res=>{
                    console.log(res)
                    if(res.code==200){
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false
                        this.loadPost()
                        this. resetForm()
                    }else{
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }

                })
            },
            save() {
              this.$refs.form.validate((valid) => {
                if (valid) {
                  // 检查总金额、支付方式和状态是否为空
                  if (!this.form.totalAmount || this.form.payType !== 0 ) {
                      if(!this.form.status){
                        // 如果任何一个字段为空，则显示错误消息并阻止表单提交
                        this.$message({
                          message: '操作失败，总金额、支付方式和状态不能为空！',
                          type: 'error'
                        });
                        return false;
                      }
                  }
                  // 如果表单验证通过且所有必填字段都不为空，则执行保存操作
                  if(this.form.id){
                    this.doMod();
                  }else{
                    this.doSave();
                  }
                } else {
                  console.log('error submit!!');
                  return false;
                }
              });
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageNum=1
                this.pageSize=val
                this.loadPost()
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum=val
                this.loadPost()
            },
            resetParam(){
                this.name=''
            },
            loadPost(){
                this.$axios.post(this.$httpUrl+'/order/listPage',{
                    pageSize:this.pageSize,
                    pageNum:this.pageNum,
                    param:{
                        name:this.name
                    }
                }).then(res=>res.data).then(res=>{
                    console.log(res)
                    if(res.code==200){
                        this.tableData=res.data
                        this.total=res.total
                    }else{
                        alert('获取数据失败')
                    }

                })
            },
            getIncrease(num, digit) {
              var increase = "";
              for (var i = 0; i < digit; i++) {
                increase += "0";
              }
              return (increase + num).slice(-digit);
            }
        },
        beforeMount() {
            this.lastId = parseInt(localStorage.getItem('lastId')) || 0;
            this.getTime();
            this.loadPost();
            this.loadReturnReasons();
            this.$store.dispatch('fetchOrderSettings', this.$httpUrl);
            // 初始化时为每行数据添加一个 selected 属性
            this.tableData.map(item => item.selected = false);
        },
        computed:{
          ...mapState({
            orderSetting: state => state.orderSettings
          })
        }

    }
</script>